/*
 * Created by kopper on 01.02.15 09:00
 * (C) Copyright 2015 kopperek@gmail.com
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 */

package app.android.kopper.gpxdownloader;

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;

import java.io.IOException;

public class UsbDevice {

    private final int TIMEOUT=1000;

    private final UsbManager manager;
    private final UsbEndpoint input;
    private final UsbEndpoint output;
    private final UsbInterface intf;
    private final android.hardware.usb.UsbDevice device;
    private final UsbDeviceDef usbDeviceDef;

    public UsbDevice(UsbManager manager,android.hardware.usb.UsbDevice device,UsbEndpoint input,UsbEndpoint output,UsbInterface intf,UsbDeviceDef usbDeviceDef) {
        this.manager=manager;
        this.device=device;
        this.input=input;
        this.output=output;
        this.intf=intf;
        this.usbDeviceDef=usbDeviceDef;
    }

    public UsbDeviceDef getUsbDeviceDef() {
        return usbDeviceDef;
    }

    public android.hardware.usb.UsbDeviceConnection openConnection() throws IOException {
        return manager.openDevice(device);
    }

    public int send(UsbDeviceConnection connection,byte[] bytes) {
        return connection.bulkTransfer(output,bytes,bytes.length,TIMEOUT);
    }

    public int receive(UsbDeviceConnection connection,byte[] bytes) {
        return connection.bulkTransfer(input,bytes,bytes.length,TIMEOUT);
    }

    public byte[] receiveFully(UsbDeviceConnection connection, int bytesCount, IUtilProvider utils) throws IOException {
        byte[] result=new byte[bytesCount];
        int offset=0;
        int length=bytesCount;
        for(;;) {
            byte[] subResult=new byte[length];
            int received=connection.bulkTransfer(input,subResult,length,TIMEOUT);
            if(received<0)
                throw new IOException(utils.getString(R.string.error_communication)+" ("+received+")");
            received=Math.min(received,length); //?
            System.arraycopy(subResult,0,result,offset,received);
            length-=received;
            if(length==0)
                break;
            offset+=received;
        }
        return result;
    }

    public void close(UsbDeviceConnection connection) {
        connection.releaseInterface(intf);
    }
}
